package com.jieshen;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TalkServer {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;

        ByteArrayOutputStream baos = null;
        try {
            ss = new ServerSocket(9090);
            socket = ss.accept();
            is = socket.getInputStream();
            os = socket.getOutputStream();
            while(true) {
                //接收信息
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(socket.getInetAddress().getHostAddress() + ": " + baos);

                //字符串传出去
                String s1 = s.nextLine();
                os.write(s1.getBytes());

                //添加写完的标志
                socket.shutdownOutput();

                if("e".equalsIgnoreCase(s1)||"e".equalsIgnoreCase(baos.toString()))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        if(baos!=null){
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if(is!=null)
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(socket!=null)
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(ss!=null)
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(os!=null)
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        s.close();
    }
}
